package com.zl.bootsecurityjwt.controller;
import com.zl.bootsecurityjwt.common.annotation.ExtAuthorize;
import com.zl.bootsecurityjwt.common.constant.HttpStatus;
import com.zl.bootsecurityjwt.common.jwt.JwtTokenTemplate;
import com.zl.bootsecurityjwt.common.result.AjaxResult;
import com.zl.bootsecurityjwt.model.JwtParam;
import com.zl.bootsecurityjwt.service.JwtUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;


/**
 * 测试控制类
 *
 * 作者：周浪
 * 时间：2021-11-12
 */
@RestController
@RequestMapping(value = "auth")
public class HelloJwtController {

    @Autowired
    private JwtTokenTemplate jwtTokenTemplate;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @PostMapping(value = "login")
        public AjaxResult login(@RequestBody JwtParam body) throws AuthenticationException {
        String token="";
        if(body.getUsername().isEmpty() || body.getPassword().isEmpty()){
            return new AjaxResult(HttpStatus.ERROR,"用户名和密码不能为空，请重新输入");
        }else {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(body.getUsername(), body.getPassword());
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = userDetailsService.loadUserByUsername(body.getUsername());
            token=jwtTokenTemplate.generateToken(userDetails);
        }

        return new AjaxResult(HttpStatus.SUCCESS,"token令牌",token);
    }

    @GetMapping(value = "hello")
    @ExtAuthorize(hasExtPermi="user:list")
    public String hello() {
        return "Hello Jwt!!!";
    }

}